package service

import (
	"encoding/json"
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/client"
	dysmsapi "github.com/alibabacloud-go/dysmsapi-20170525/v2/client"
	"github.com/gin-gonic/gin"
	"log"
	"main/dao"
	"main/model"
	"main/param"
	"main/tool"
	"math/rand"
	"strconv"
	"time"
)

type MemberService struct {
	
}

func (ms *MemberService) GetUserInfo(userId string) *model.Member {
	md := dao.MemberDao{
		OrmEngine: tool.DbEngine,
	}
	// 根据Id查询
	id, err := strconv.Atoi(userId)
	if err != nil {
		return nil
	}
	return md.QueryUserById(int64(id))
}

func (ms *MemberService) UploadAvatar(userId int64, fileName string) string {
	md := dao.MemberDao{
		OrmEngine: tool.DbEngine,
	}
	uid := md.UploadMemberAvatar(userId, fileName)
	if uid == 0 {
		return ""
	}
	return fileName
}

func (ms *MemberService) Login(name string, password string) *model.Member {
	// 1 用户存在
	md := dao.MemberDao{
		OrmEngine: tool.DbEngine,
	}
	member := md.QueryByLogin(name, tool.EncodePassword(password))
	if member.Id != 0 {
		return member
	}

	// 2 用户不存在,作为新用户插入
	user := model.Member{
		UserName:     name,
		Mobile:       "",
		Password:     tool.EncodePassword(password),
		RegisterTime: time.Now().Unix(),
	}
	user.Id = md.InsertMember(user)
	return &user
}

// SmsLogin 用户手机号+验证码登录
func (ms *MemberService) SmsLogin(smsLoginParam param.SmsLoginParam) *model.Member {
	// 1. 获取参数,验证参数
	md := dao.MemberDao{
		OrmEngine: tool.DbEngine,
	}
	sms := md.ValidateSmsCode(smsLoginParam.Phone, smsLoginParam.Code)
	if sms.Id == 0 {
		return nil
	}

	// 2. 查询member纪录
	member := md.QueryByPhone(smsLoginParam.Phone)
	if member.Id != 0 {
		// 查询到记录
		return member
	}
	//没有查询到记录

	// 3. 新建member并保存
	user := model.Member{
		UserName:     smsLoginParam.Phone,
		Mobile:       smsLoginParam.Phone,
		RegisterTime: time.Now().Unix(),
	}
	user.Id = md.InsertMember(user)
	return &user
}

func (ms *MemberService) SendCode(phone string) bool {
	// 1 生成验证码
	code := fmt.Sprintf("%06v", rand.New(
			rand.NewSource(
				time.Now().UnixNano(),
			),
		).Int31n(1000000), // 几位就保留几个0
	)

	// 2 调用阿里sdk
	smsConfig := tool.GetConfig().Sms
	cli, err := dysmsapi.NewClient(&openapi.Config{
		AccessKeyId:          &smsConfig.AppKey,
		AccessKeySecret:      &smsConfig.AppSecret,
		RegionId:             &smsConfig.RegionId,
	})
	if err != nil {
		log.Printf(err.Error())
		return false
	}

	bts, err := json.Marshal(gin.H{
		"code": code,
	})
	if err != nil {
		log.Printf(err.Error())
		return false
	}
	tempParam := string(bts)
	req := &dysmsapi.SendSmsRequest{
		PhoneNumbers:         &phone,
		SignName:             &smsConfig.SignName,
		TemplateCode:         &smsConfig.TemplateCode,
		TemplateParam:		  &tempParam,
	}
	res, err := cli.SendSms(req)

	// 3 处理返回
	if err == nil && *(res.Body.Code) == "OK" {
		smsCode := model.SmsCode{
			Phone:      phone,
			BizId:      *(res.Body.BizId),
			Code:       code,
			CreateTime: time.Now().Unix(),
		}
		memberDao := dao.MemberDao{
			OrmEngine: tool.DbEngine,
		}
		result := memberDao.InsertCode(smsCode)
		return result > 0
	} else {
		log.Printf(err.Error())
		return false
	}
}




